<template>
<view class="body">
	<view class="header">
		<!--<scroll-view id="scrollpage" class="history" scroll-y="true" :scroll-top="height3" 
		:scroll-into-view="toView" scroll-with-animation="true" bindscroll="sceollTop" 
		enhanced="true">-->
		<scroll-view scroll-y="true" @scroll="sceollTop" class="history" :scroll-into-view="toView">
			<block v-for="(item,index) in list" :key="index" class="content">
				<view class='my_right' v-if="item.uid == uid" :id='"AM"+index'>
					<text class="time" v-if="item.addtime">{{item.addtime}}</text>
					<view class='p_r'>
						<!-- <view class='new_txt' v-if="showArr[index]">
							<view class='new_txt_content'>
								<view @click="addWord(item.content,index)">添加常用语</view>
								<view @click="closeShow(index)">取    消</view>
							</view>
						</view> -->
						<view class='new_txt' @longpress="longTime(index)">
							<view class='new_txt_my'>{{item.content}}
								<view class='new_txt_content'v-if="showArr[index]">
									<view @click="addWord(item.content,index)">添加常用语</view>
									<view @click="closeShow(index)">取    消</view>
								</view>
							</view>
						</view>
						
						<image v-if="uimg" class='new_img' :src='uimg'></image>
					</view>
				</view>
				<view class='you_left' v-if="item.uid == touid" :key="index" :id='"AM"+index'>
					<text class="time" v-if="item.addtime">{{item.addtime}}</text>
					<view class='p_r1'>
						<image class='new_img1' v-if="toimg" :src='toimg'></image>
						<view class='new_txt'>
							<view class='new_txt_my'>{{item.content}}</view>
						</view>
					</view>
				</view>
			</block>
		</scroll-view>
	</view>
	<view class="sendmessage">
		<view class="word_left" @click="wordsOpen">常用语</view>
		<input type="text" @input="bindKeyInput" :value='inputValue'  
		confirm-type = 'send' cursor-spacing = '10' @confirm="search"/>
		<view @click="search" class='user_input_text'>发送</view>
	</view>
	<view class="words" v-if="wordShow">
		<view class="words_title">
		    <text>常用语</text>
		    <image class="word_close" @click="wordsClose" src='/static/img/none_close.png'></image>
		</view>
		<scroll-view class="scrollBotton" scroll-y="true" scroll-top="350rpx"
		scroll-with-animation="true">
			<view class="word_line" @click="wordsSend(item.remark)" v-for="(item,index) in words" :key="index">{{item.remark}}</view>
		</scroll-view>
		<view @click="gowords" class="words_bottom">管理常用语</view>
	</view>
</view>
</template>
<script>
import request from '@/util/request.js'
export default {
	data() {
		return {
			scrollHeight:'100vh',
			height3: '',
			toView:'',
			list:[],
			wordShow:false,
			setInter:null,
			inputValue:'',
			words:[],
			toimg:'',
			showArr:[],
			IsOpen:false,
			SocketTask:false,
			// 是否上线
			IsOnline:false,
			socketTask:null,
			messageList:[],
			timeout:0,
			timeoutObj:null
		}
	},
	onLoad:function(e) {
		var touid = e.touid
		this.touid = touid
		// this.uid = uni.getStorageSync('uid')
		// this.uimg = uni.getStorageSync('avatarUrl')
		// this.getList()
		// this.getInfo()
		this.socketInit()
		//var that = this
		// this.setInter = setInterval(function(){
		// 	that.getList();
		// },2000)
	},
	onUnload: function() {
		//console.log('释放')
		var that = this
		//console.log(this.setInter)
		if(this.setInter) {
			clearInterval(this.setInter);  
			this.setInter = null;
			//console.log(this.setInter)
		}
	},
	onHide:function(){
		//console.log('释放22')
		var that = this
	    if(this.setInter) {
	    	clearInterval(this.setInter);  
	    	that.setInter = null;    
	    }
	},
	methods: {
		socketInit:function(){
			var that =this
			//判断是否否已连接
			uni.sendSocketMessage({
				data: 'ping',
				success: (res) => {
					// uni.sendSocketMessage({
					// 	data:'type=add&ming=2',
					// 	success(res) {
					// 		console.log(res);
					// 		console.log("消息发送成功");
					// 	}
					// });
					console.log('一直在线',res)
					return;
				},
				fail: (err) => { // 未连接打开websocket连接
					that.openConnection();
				}
			});
			// this.socketTask = uni.connectSocket({				// 【非常重要】必须确保你的服务器是成功的,如果是手机测试千万别使用ws://127.0.0.1:9099【特别容易犯的错误】
			// 	url: 'ws://47.94.242.46:9501/'+that.touid,
			// 	success(data) {
			// 		console.log(data,'连接成功')
			// 	},
			// });
			// this.socketTask.onOpen((res) => {
			// 	that.IsOpen = true
				
			// })
			// //创建一个socket连接
			// uni.connectSocket({
			//   url: 'ws://47.94.242.46:9501',
			//   success: res=>{}
			// });
			// //监听socket打开
			// uni.onSocketOpen(function (res) {
			// 	this.IsOpen = true
			// 	console.log('WebSocket连接已打开！');
			// });
			// //监听socket关闭
			// uni.onSocketClose(()=>{
			// 	this.IsOpen = false
			// 	console.log('WebSocket连接已关闭！');
			// })
			// //监听socket错误
			// uni.onSocketError(function (res) {
			//   console.log('WebSocket连接打开失败，请检查！');
			// });
			// //监听socket消息
			// uni.onSocketMessage(function (res) {
			// 	console.log(res);
			// });
			//先确保清除了之前的心跳定时器
			// clearInterval(this.pingpangTimes)
			// //每过一段时间发送一次心跳，发送Ping,服务器会反馈pong，这样操作以保持socket一直是连接状态，防止断开连接，心跳停止
			// this.pingpangTimes=setInterval(()=>{
			// 	uni.sendSocketMessage({
			// 		data: "ping",
			// 		success:()=>{},
			// 		fail:()=>{
			// 			this.isSocketOpen=false
			// 		}
			// 	});
			// },60000)
		},
		openConnection:function(){
			// 确保已经关闭后再重新打开
			uni.closeSocket();
			uni.connectSocket({
				// 【非常重要】必须确保你的服务器是成功的
				url: "ws://47.94.242.46:9501",
				success(data) {
					console.log("websocket正在连接...",data);
				},
			});
			// 消息的发送和接收必须在正常连接打开中,才能发送或接收【否则会失败】
			uni.onSocketOpen(function (res) {
				 console.log('WebSocket连接成功',res);
			});
			//连接成功后如果有服务器返回的消息 先接收
			this.onSocketMessage(2); 
		},
		onSocketMessage:function(type = 1){
			this.timeout = 60000;
			this.timeoutObj = null;
			uni.onSocketMessage((res) => {
				let backMsg = res.data;
				console.log('返回数据',JSON.parse(backMsg));
				// 后台绑定client_id
				// 如果返回有数据 转换
				// if (backMsg) {
				// 	let msg = JSON.parse(backMsg);
				// 	console.log('返回数据',msg);
					
				// 	if (msg.type ===  'init' || type === 2) {
				// 		console.log("判断是否有数据"+backMsg)
				// 		let clientId =  msg.client_id;
				// 		let userId = uni.getStorageSync('userInfo');
				// 		let para = {client_id: clientId, userId : userId  };
				// 		console.log("触发心跳")
				// 		this.reset(); 
				
				// 	}
				//}
				// 如果没连接成功服务器并没有返回数据
				//this.getSocketMsg(res.data); // 监听到有新服务器消息
			})
		},
		getList:function(){
		    var that = this
		    var data = {
				'uid':uni.getStorageSync('uid'),
				'touid':this.touid,
			}
			request({
				url: 'online/list',
				method: 'get',
				data:data,
				success: (res) => {
					if(res.data.code == 1){
						var str = res.data.data.length - 1;
						that.list = res.data.data
						that.$nextTick(()=> {
							that.toView = 'AM' + str
						});
						//that.toView = 'AM'+ str
						//console.log('开始',that.toView)
					}
				}
			})
		},
		getInfo:function(){
			var that = this
			var data = {'uid':this.touid}
			request({
				url: 'member/status',
				method: 'get',
				data:data,
				success: (res) => {
					if(res.data.code == 1){
						that.toimg = res.data.data.avatar
					}
				},
			})
		},
		wordsOpen:function(){
			var that = this
			var data = {uid:uni.getStorageSync('uid')}
			request({
				url: 'problem/words',
				method: 'get',
				data:data,
				success: (res) => {
					if(res.data.code == 1){
						that.wordShow = true
						that.words = res.data.data
					}
				}
			})
		},
		wordsSend:function(item){
			this.inputValue = item
			this.wordShow = false
			this.send()
		},
		send:function(){
		    if(!this.inputValue){
		      return;
		    } 
			uni.sendSocketMessage({
				data:'type=only&uid=2&touid=3',
				success(res) {
					console.log(res);
					console.log("消息发送成功");
				}
			});
			// let content = this.replaceEmoji(this.textMsg);
			// let msg = {text:content}
			// this.sendMsg(msg,'text');
			// this.textMsg = '';//清空输入框
			// var data = {
			// 	uid:uni.getStorageSync('uid'),
			// 	touid:this.touid,
			// 	content:this.inputValue,
			// }
			// uni.sendSocketMessage({
			// 	data:JSON.stringify(data),
			// 	success: (res) => {
			// 		console.log('发送成功',res)
			// 	},
			// 	fail:(err) => {
			// 		console.log(err)
			// 	}
			// })
			return;
		    var that = this
		    var data = {
				'uid':uni.getStorageSync('uid'),
				'touid':this.touid,
				'content':this.inputValue,
			}
		    var list = that.list
			request({
				url: 'online/add',
				method: 'post',
				data:data,
				success: (res) => {
					that.inputValue = '',
					that.list = list.concat(data)
				}
			})
		},
		bindKeyInput:function(e){
			this.inputValue = e.detail.value
		},
		search:function(){
			this.send()
		},
		sceollTop:function(e){
			var that = this
		    var type = e.detail.deltaY
		    if(type > 0){//上滑动
				//console.log('上划释放')
				if(this.setInter) {
					clearInterval(that.setInter);  
					that.setInter = null;  
				}
		    }else{//下滑动
				if(!this.setInter){
					that.setInter = setInterval(function(){
						//console.log('下划执行')
					    that.getList();
					},2000)
				}
			}
		 },
		 gowords:function(){
		 	uni.navigateTo({
		 		url:'/pages/message/online/words'
		 	});
		 },
		 wordsClose:function(){
			 this.wordShow = false
		},
		longTime:function(index){
			this.showArr[index] = true
			this.$forceUpdate();
		},
		closeShow:function(index){
			this.showArr[index] = false
			this.$forceUpdate();
		},
		addWord:function(content,index){
			var data = {
				uid:uni.getStorageSync('uid'),
				remark:content
			}
			var that = this
			request({
				url: 'problem/wordsAdd',
				method: 'post',
				data:data,
				success: (res) => {
					that.showArr[index] = false
					that.$forceUpdate();
				}
			})
		}
	}
}
</script>
<style scoped>
	@import url("./css/toCompany.css");
</style>